package com.example.demo.controller;

import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * Description: 流程实例查询控制器
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author 作者名称 用户名
 * @date 2025/1/15 17:29
 */
@RestController
@RequestMapping("/api/process-instance")
public class ProcessInstanceController {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    /**
     * 查询流程实例的当前任务和责任人
     *
     * @param processInstanceId 流程实例ID
     * @return 流程实例信息
     * @author 作者姓名
     * 
     * 
     * @date 2025/1/15 17:29
     */
    @GetMapping("/{processInstanceId}/current-tasks")
    public Map<String, Object> getCurrentTasks(@PathVariable String processInstanceId) {
        Map<String, Object> result = new HashMap<String, Object>();
        
        try {
            // 查询流程实例基本信息
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            
            if (processInstance == null) {
                // 如果运行时查询不到，可能是已完成的流程，查询历史
                HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                        .processInstanceId(processInstanceId)
                        .singleResult();
                
                if (historicProcessInstance != null) {
                    result.put("status", "COMPLETED");
                    result.put("processInstanceId", historicProcessInstance.getId());
                    result.put("processDefinitionId", historicProcessInstance.getProcessDefinitionId());
                    result.put("processDefinitionKey", historicProcessInstance.getProcessDefinitionKey());
                    result.put("startTime", historicProcessInstance.getStartTime());
                    result.put("endTime", historicProcessInstance.getEndTime());
                    result.put("duration", historicProcessInstance.getDurationInMillis());
                    result.put("startUserId", historicProcessInstance.getStartUserId());
                    result.put("deleteReason", historicProcessInstance.getDeleteReason());
                    result.put("message", "流程已完成，无当前任务");
                } else {
                    result.put("error", "流程实例不存在");
                }
                return result;
            }
            
            // 流程实例基本信息
            result.put("status", "ACTIVE");
            result.put("processInstanceId", processInstance.getId());
            result.put("processDefinitionId", processInstance.getProcessDefinitionId());
            result.put("processDefinitionKey", processInstance.getProcessDefinitionKey());
            result.put("businessKey", processInstance.getBusinessKey());
            result.put("startTime", processInstance.getStartTime());
            result.put("startUserId", processInstance.getStartUserId());
            
            // 查询当前任务
            List<Task> activeTasks = taskService.createTaskQuery()
                    .processInstanceId(processInstanceId)
                    .active()
                    .list();
            
            if (activeTasks.isEmpty()) {
                result.put("currentTasks", "无当前任务");
                result.put("message", "流程实例存在但无活跃任务");
            } else {
                result.put("currentTasks", activeTasks.size());
                
                // 详细任务信息
                for (Task task : activeTasks) {
                    Map<String, Object> taskInfo = new HashMap<String, Object>();
                    taskInfo.put("taskId", task.getId());
                    taskInfo.put("taskName", task.getName());
                    taskInfo.put("taskDefinitionKey", task.getTaskDefinitionKey());
                    taskInfo.put("assignee", task.getAssignee());
                    // 注意：Flowable 7.x中需要通过IdentityService查询候选用户和组
                    taskInfo.put("candidateUsers", "需要通过IdentityService查询");
                    taskInfo.put("candidateGroups", "需要通过IdentityService查询");
                    taskInfo.put("createTime", task.getCreateTime());
                    taskInfo.put("dueDate", task.getDueDate());
                    taskInfo.put("priority", task.getPriority());
                    taskInfo.put("description", task.getDescription());
                    taskInfo.put("owner", task.getOwner());
                    taskInfo.put("delegationState", task.getDelegationState());
                    taskInfo.put("parentTaskId", task.getParentTaskId());
                    taskInfo.put("tenantId", task.getTenantId());
                    
                    // 任务变量
                    Map<String, Object> variables = taskService.getVariables(task.getId());
                    taskInfo.put("variables", variables);
                    
                    result.put("task_" + task.getId(), taskInfo);
                }
            }
            
        } catch (Exception e) {
            result.put("error", "查询失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 查询流程实例的所有任务（包括历史任务）
     *
     * @param processInstanceId 流程实例ID
     * @return 所有任务信息
     * @author 作者姓名
     * @date 2025/1/15 17:29
     */
    @GetMapping("/{processInstanceId}/all-tasks")
    public Map<String, Object> getAllTasks(@PathVariable String processInstanceId) {
        Map<String, Object> result = new HashMap<String, Object>();
        
        try {
            // 查询历史任务
            List<org.flowable.task.api.history.HistoricTaskInstance> historicTasks = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .orderByHistoricTaskInstanceStartTime()
                    .asc()
                    .list();
            
            result.put("processInstanceId", processInstanceId);
            result.put("totalTasks", historicTasks.size());
            
            for (org.flowable.task.api.history.HistoricTaskInstance task : historicTasks) {
                Map<String, Object> taskInfo = new HashMap<String, Object>();
                taskInfo.put("taskId", task.getId());
                taskInfo.put("taskName", task.getName());
                taskInfo.put("taskDefinitionKey", task.getTaskDefinitionKey());
                taskInfo.put("assignee", task.getAssignee());
                // 注意：Flowable 7.x中需要通过IdentityService查询候选用户和组
                taskInfo.put("candidateUsers", "需要通过IdentityService查询");
                taskInfo.put("candidateGroups", "需要通过IdentityService查询");
                taskInfo.put("startTime", task.getStartTime());
                taskInfo.put("endTime", task.getEndTime());
                taskInfo.put("duration", task.getDurationInMillis());
                taskInfo.put("deleteReason", task.getDeleteReason());
                taskInfo.put("priority", task.getPriority());
                taskInfo.put("description", task.getDescription());
                taskInfo.put("owner", task.getOwner());
                taskInfo.put("delegationState", task.getDeleteReason());
                taskInfo.put("parentTaskId", task.getParentTaskId());
                taskInfo.put("tenantId", task.getTenantId());
                
                result.put("task_" + task.getId(), taskInfo);
            }
            
        } catch (Exception e) {
            result.put("error", "查询失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 查询流程实例的流程变量
     *
     * @param processInstanceId 流程实例ID
     * @return 流程变量
     * @author 作者姓名
     * @date 2025/1/15 17:29
     */
    @GetMapping("/{processInstanceId}/variables")
    public Map<String, Object> getProcessVariables(@PathVariable String processInstanceId) {
        Map<String, Object> result = new HashMap<String, Object>();
        
        try {
            // 查询流程变量
            Map<String, Object> variables = runtimeService.getVariables(processInstanceId);
            result.put("processInstanceId", processInstanceId);
            result.put("variables", variables);
            result.put("variableCount", variables.size());
            
        } catch (Exception e) {
            result.put("error", "查询失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 查询流程实例的流程图
     *
     * @param processInstanceId 流程实例ID
     * @return 流程图信息
     * @author 作者姓名
     * @date 2025/1/15 17:29
     */
    @GetMapping("/{processInstanceId}/diagram")
    public Map<String, Object> getProcessDiagram(@PathVariable String processInstanceId) {
        Map<String, Object> result = new HashMap<String, Object>();
        
        try {
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            
            if (processInstance != null) {
                result.put("processInstanceId", processInstanceId);
                result.put("processDefinitionId", processInstance.getProcessDefinitionId());
                result.put("processDefinitionKey", processInstance.getProcessDefinitionKey());
                result.put("message", "流程图可通过Flowable Modeler查看，或使用ProcessDiagramGenerator生成");
            } else {
                result.put("error", "流程实例不存在或已完成");
            }
            
        } catch (Exception e) {
            result.put("error", "查询失败: " + e.getMessage());
        }
        
        return result;
    }
}
